import {defineStore} from 'pinia'
import {computed, ref} from 'vue'
import {getCurrentUserInfo, login, logout, register} from '@/api/user'
import {getToken, removeToken, setToken} from '@/utils/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(getToken())
  const userInfo = ref(null)
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const avatar = computed(() => userInfo.value?.avatar || '')
  const nickname = computed(() => userInfo.value?.nickname || userInfo.value?.username || '')
  const username = computed(() => userInfo.value?.username || '')

  // 登录
  const loginAction = async (loginForm) => {
    loading.value = true
    try {
      const response = await login(loginForm)
      if (response.code === 200) {
        const loginData = response.data
        // 保存token
        token.value = loginData.token
        setToken(loginData.token)

        // 保存用户基本信息
        userInfo.value = {
          userId: loginData.userId,
          username: loginData.username,
          nickname: loginData.nickname,
          avatar: loginData.avatar
        }

        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      return { success: false, message: error.message || '登录失败' }
    } finally {
      loading.value = false
    }
  }

  // 注册
  const registerAction = async (registerForm) => {
    loading.value = true
    try {
      const response = await register(registerForm)
      if (response.code === 200) {
        return { success: true, message: '注册成功' }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      return { success: false, message: error.message || '注册失败' }
    } finally {
      loading.value = false
    }
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    if (!token.value) return

    try {
      const response = await getCurrentUserInfo()
      if (response.code === 200) {
        // 更新用户信息，保持userId字段一致性
        const userData = response.data
        userInfo.value = {
          ...userData,
          userId: userData.userId || userData.id
        }
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果token无效，清除登录状态
      if (error.response?.status === 401) {
        logoutAction()
      }
    }
  }

  // 刷新用户信息
  const refreshUserInfo = async () => {
    await getUserInfoAction()
  }

  // 登出
  const logoutAction = async () => {
    try {
      await logout()
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      token.value = ''
      userInfo.value = null
      removeToken()
    }
  }

  // 初始化用户信息
  const initUserInfo = async () => {
    if (token.value) {
      await getUserInfoAction()
    }
  }

  // 更新用户信息
  const updateUserInfo = (newUserInfo) => {
    userInfo.value = { ...userInfo.value, ...newUserInfo }
  }

  return {
    // 状态
    token,
    userInfo,
    loading,
    
    // 计算属性
    isLoggedIn,
    avatar,
    nickname,
    username,
    
    // 方法
    loginAction,
    registerAction,
    getUserInfoAction,
    refreshUserInfo,
    logoutAction,
    initUserInfo,
    updateUserInfo
  }
})
